<script setup>
// ===== 导入区域 =====
import { onMounted, ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { getGoodsOutboundList, deleteGoodsOutboundById } from '@/api/goodsOutbound'
import AddGoodsOutbound from './components/AddGoodsOutbound.vue'
import logger from '@/utils/logger'
import { formatDateTime } from '@/utils/dayjs'
import { CHECK_STATUS, getCheckStatusText, getCheckStatusType } from '@/constants'

// ===== 变量声明区域 =====
/**
 * @description 控制添加/编辑对话框的显示状态
 */
const dialogVisible = ref(false)

/**
 * @description 当前操作的出库单数据
 */
const currentOutbound = ref(null)

/**
 * @description 表格数据列表
 */
const tableData = ref([])

/**
 * @description 表格加载状态
 */
const loading = ref(false)

/**
 * @description 组件模式：0-新增，1-编辑，2-审核，3-预览
 */
const mode = ref(0)

/**
 * @description 请求参数对象，包含分页和查询条件
 */
const requestParams = ref({
  currentPage: 1,
  pageSize: 10,
  queryFields: {
    outboundNo: '', // 出库单号
  },
})

/**
 * @description 分页 - 总记录数
 */
const total = ref(0)

// ===== 方法区域 =====

/**
 * @description 对话框相关方法
 */

/**
 * @description 打开对话框，根据type区分添加或编辑模式
 * @param {Object|null} row 要编辑的出库单数据，添加模式下为null
 * @param {Number} type 对话框类型：0-添加，1-编辑，2-审核，3-预览
 */
const openDialog = (row, type) => {
  currentOutbound.value = row
  mode.value = type
  dialogVisible.value = true
}

/**
 * @description 关闭对话框
 */
const closeDialog = () => {
  dialogVisible.value = false
}

/**
 * @description 数据操作相关方法
 */

/**
 * @description 获取出库单据数据列表
 */
const fetchOutboundData = async () => {
  try {
    loading.value = true
    // 处理查询参数
    const params = {
      ...requestParams.value,
      queryFields: {
        outboundNo: requestParams.value.queryFields.outboundNo.trim() || null,
      },
    }
    const res = await getGoodsOutboundList(params)
    if (res.success && res.data) {
      tableData.value = res.data.list || []
      total.value = res.data.total || 0
    } else {
      tableData.value = []
      total.value = 0
      ElMessage.error(res.msg || '获取出库单据列表失败')
    }
  } catch (error) {
    logger.error('获取出库单据列表失败', error)
    ElMessage.error('获取出库单据列表失败')
  } finally {
    loading.value = false
  }
}

/**
 * @description 直接删除出库单
 * @param {string} id 出库单ID
 */
const handleDeleteDirect = async (id) => {
  try {
    loading.value = true
    const res = await deleteGoodsOutboundById(id)
    if (res.success) {
      ElMessage.success('删除成功')
      await fetchOutboundData()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    logger.error('删除出库单据失败', error)
    ElMessage.error('删除出库单据失败')
  } finally {
    loading.value = false
  }
}

/**
 * @description 搜索相关方法
 */

/**
 * @description 执行搜索操作
 */
const handleSearch = () => {
  requestParams.value.currentPage = 1 // 搜索时重置为第一页
  fetchOutboundData()
}

/**
 * @description 重置搜索条件
 */
const resetSearch = () => {
  requestParams.value.queryFields.outboundNo = ''
  requestParams.value.currentPage = 1
  fetchOutboundData()
}

/**
 * @description 分页相关方法
 */

/**
 * @description 处理每页显示条数变化
 * @param {number} val 新的每页显示条数
 */
const handleSizeChange = (val) => {
  requestParams.value.pageSize = val
  fetchOutboundData()
}

/**
 * @description 处理当前页码变化
 * @param {number} val 新的页码
 */
const handleCurrentChange = (val) => {
  requestParams.value.currentPage = val
  fetchOutboundData()
}

/**
 * @description 工具方法
 */
/**
 * @description 格式化审核状态
 * @param {number} isCheck 是否已审核
 * @returns {string} 审核状态文本
 */
const formatCheckStatus = (isCheck) => {
  return getCheckStatusText(isCheck)
}

// ===== Vue 特殊写法 =====

/**
 * @description 组件挂载时初始化数据
 */
onMounted(() => {
  fetchOutboundData()
})

/**
 * @description 计算属性：根据模式动态设置对话框标题
 */
const dialogTitle = computed(() => {
  switch (mode.value) {
    case 0:
      return '添加出库单'
    case 1:
      return '编辑出库单'
    case 2:
      return '审核出库单'
    case 3:
      return '出库单详情'
    default:
      return '出库单'
  }
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="80%"
    destroy-on-close
    align-center
    @close="closeDialog"
  >
    <AddGoodsOutbound
      :mode="mode"
      :current-outbound="currentOutbound"
      @success="fetchOutboundData"
      @close="closeDialog"
    />
  </el-dialog>

  <div class="main-container">
    <div class="controller-container">
      <div class="controller-item">
        <el-form :inline="true" :model="requestParams.queryFields" @submit.prevent="handleSearch">
          <el-form-item label="出库单号">
            <el-input
              v-model="requestParams.queryFields.outboundNo"
              placeholder="请输入出库单号"
              clearable
              style="width: 200px"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><LineMdSearch /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <template #icon>
                <el-icon><LineMdSearch /></el-icon>
              </template>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <template #icon>
                <el-icon><LineMdClose /></el-icon>
              </template>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="controller-item">
        <el-form-item>
          <el-button type="primary" @click="openDialog(null, 0)">
            <template #icon>
              <el-icon><LineMdPlus /></el-icon>
            </template>
            添加出库单
          </el-button>
        </el-form-item>
      </div>
    </div>
    <div class="table-container">
      <el-table v-loading="loading" :data="tableData">
        <el-table-column prop="outboundNo" label="出库单号" min-width="150" align="center" />
        <el-table-column label="出库时间" min-width="180" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.outboundTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="operatorName" label="出库人" width="120" align="center" />
        <el-table-column label="审核状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getCheckStatusType(row.isCheck)">
              {{ formatCheckStatus(row.isCheck) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="checkerName" label="审核人" width="120" align="center" />
        <el-table-column label="审核时间" min-width="180" align="center">
          <template #default="{ row }">
            {{ row.checkTime ? formatDateTime(row.checkTime) : '未审核' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="notes"
          label="备注"
          min-width="180"
          :show-overflow-tooltip="true"
          align="center"
        />
        <el-table-column label="操作" min-width="300" fixed="right" align="center">
          <template #default="{ row }">
            <!-- 未审核状态显示审核按钮 -->
            <template v-if="row.isCheck === CHECK_STATUS.UNCHECKED">
              <el-button type="success" size="small" @click="openDialog(row, 2)">
                <template #icon>
                  <el-icon><LineMdCheckAll /></el-icon>
                </template>
                审核
              </el-button>
            </template>
            <!-- 未审核状态显示编辑按钮 -->
            <template v-if="row.isCheck === CHECK_STATUS.UNCHECKED">
              <el-button type="primary" size="small" @click="openDialog(row, 1)">
                <template #icon>
                  <el-icon><LineMdEdit /></el-icon>
                </template>
                编辑
              </el-button>
            </template>

            <el-button type="info" size="small" @click="openDialog(row, 3)">
              <template #icon>
                <el-icon><LineMdWatchLoop /></el-icon>
              </template>
              详情
            </el-button>

            <!-- 未审核状态显示删除按钮 -->
            <template v-if="row.isCheck === CHECK_STATUS.UNCHECKED">
              <el-popconfirm
                placement="top-start"
                confirm-button-text="确定"
                cancel-button-text="取消"
                :title="`确定要删除出库单 '${row.outboundNo}' 吗？`"
                width="250"
                confirm-button-type="danger"
                @confirm="handleDeleteDirect(row.goodsOutboundMId)"
              >
                <template #reference>
                  <el-button type="danger" size="small">
                    <template #icon>
                      <el-icon><LineMdTrash /></el-icon>
                    </template>
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="requestParams.currentPage"
          v-model:page-size="requestParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.main-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 10px;
  .controller-container {
    border-radius: 10px;
    background-color: #fff;
    .controller-item {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }
  .table-container {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border-radius: 10px;
    padding: 10px;
    overflow: hidden;
    gap: 10px;

    .el-table {
      flex: 1;
    }
  }
  .pagination-container {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
